# -*- coding: UTF-8 -*-
# 使用先到先服务（FCFS）算法，得到对比结果
import random
import AoI_SP
from seller_SP import SellerAoISP
from buyer_SP import BuyerAoISP
from util import Util


def FCFS(T, s, b):
    qseller = len(s)  # 数据源数量
    tfirst = []  # 首次更新时间
    sindex = []  # 数据源序号
    for seller in s:
        tfirst.append(seller.updates[0])
        sindex.append(seller.id)
    # 按照首次更新时间，简单插入排序
    for i in range(1, qseller):
        key = tfirst[i]
        keyid = sindex[i]
        j = i-1
        while j >= 0 and key < tfirst[j]:
            tfirst[j+1] = tfirst[j]
            sindex[j+1] = sindex[j]
            j -= 1
        tfirst[j+1] = key
        sindex[j+1] = keyid
    bw = []  # 各个买家选择结果集合
    baoi = []
    # 每个买家按顺序雇佣数据源
    for buyer in b:
        budget = buyer.budget
        w = []
        for i in range(qseller):
            index = sindex[i]
            if budget < s[index].price[buyer.id]:
                continue
            w.append(index)
            budget -= s[index].price[buyer.id]
        bw.append(w)
        baoi.append(AoI_SP.getAoI(s, w, T))
    return bw, baoi


if(__name__ == "__main__"):
    # 参数
    qseller = 10  # 卖家数量
    qbuyer = 2  # 买家数量
    budget = 80  # 初始预算
    T = 100  # 时间段数量
    mode = 'w'  # 数据存取模式

    # 初始化
    s = []  # 卖家集合
    b = []  # 买家集合
    util = Util()
    for i in range(qseller):
        seller = SellerAoISP(i, qbuyer, T)
        s.append(seller)
    for i in range(qbuyer):
        buyer = BuyerAoISP(i, T, random.randint(budget-10, budget+10))
        b.append(buyer)
    buyerw, buyeraoi = FCFS(T, s, b)
    print(buyerw, buyeraoi)
